<script setup lang="ts">
import {Map, View} from "ol";
import * as control from 'ol/control';
import * as coordinate from 'ol/coordinate';
import TileLayer from "ol/layer/Tile";
import LayerVector from 'ol/layer/Vector'
import SourceVector from 'ol/source/Vector'
import Draw from 'ol/interaction/Draw'
import {XYZ} from "ol/source";
import {onMounted, ref} from "vue";
import source = ol.source;


const map = ref(null) // 存放地图实例
const mousePositionTxt = ref([102.064839, 24.548857])
const currentCoordinate = ref([102.064839, 24.548857])
const scaleLineControl = ref(null) //比例尺
let coordinateSign = ref(0) //是否显示经纬度
const tool = ref('Polygon')
let points = ref(null)

// 1.跟随鼠标移动显示相应经纬度（control.MousePosition)。2.显示比例尺(scaleLineControl)。3.通过TabIndex实现地图激活。4.使用多边形绘制区域并返回相应经纬度坐标(绘制：首先新建一个绘制层vector，然后通过new Draw创建绘制类。通过map.addInteraction等相关方法实现绘制操作。获取点坐标：需要在drawPoly方法中，获取点坐标（否则存在获取不到点的现象，即识别不了draw.value.on() ）。一次绘制只能获取当前图形的完整坐标（不能同时获取上一次获取到的坐标）。这里做完善的话，可以将每次产生的坐标存在本地。最后再统一返回。

const sourceDraw = new SourceVector({
  wrapX: false // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
})

// 绘图层
let vector = new LayerVector({
  source: sourceDraw
})

function initMap () {
  scaleLineControl.value = new control.ScaleLine()//默认是 米制单位
  // 地图实例
  map.value = new Map({
    target: 'map1',                         // 对应页面里 id 为 map1 的元素
    layers: [                              // 图层
      new TileLayer({
        source: new XYZ({
          url:"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f0205b3015ed23553ee037f6ecac9b19",
          wrapX: false
        }),
        preload: Infinity,//底图预加载。减少缩放时出现的空白区域。
      }),
      new TileLayer({
        source: new XYZ({
          url:"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=f0205b3015ed23553ee037f6ecac9b19",
          wrapX: false
        }),
        preload: Infinity,
      }),
      vector,
    ],
    view: new View({                       // 地图视图
      projection: "EPSG:4326",             // 坐标系，有EPSG:4326和EPSG:3857
      center: [102.8599, 24.8297],     // 深圳坐标（经纬度）
      minZoom:2,// 地图缩放最小级别
      maxZoom:18,//同时设置这两个值（min、maxZoom）之后，就能够限制缩放
      zoom: 15                             // 地图默认缩放级别（打开页面时默认级别）
    }),
    controls: control.defaults().extend([
      scaleLineControl.value, // 比例尺
      new control.MousePosition({
        coordinateFormat: coordinate.createStringXY(4),
        projection: 'EPSG:4326',
        target: mousePositionTxt.value
      })
    ])
  })
}

const draw = ref(null)

function drawPoly() {
  if (draw.value != null) {
    map.value.removeInteraction(draw.value)
  }
  if (tool.value != 'None') {
    draw.value = new Draw({
      source: sourceDraw,
      type: tool.value
    })
    map.value.addInteraction(draw.value)
    //当图形框选完之后，就会执行下面，输出点
    draw.value.on('drawend', function (event){
      let geometry = event.feature.getGeometry()
      points.value = geometry.getCoordinates()[0]
      console.log(points.value)
    })

  }
}

function drawExit() {
  if (draw.value) {
    map.value.removeInteraction(draw.value);
  }
  draw.value = null
}

function drawClear() {
  sourceDraw.clear()
  console.log(sourceDraw)

}

onMounted(() => {
  initMap()
})

function mapClick(){
  map.value.on('singleclick', evt => {
    currentCoordinate.value = evt.coordinate // 获取并保存坐标点
  })
}

function showCoordinate(){
  coordinateSign.value = 1
}
</script>

<template>
  <div class="flex w-full gap-1">
    <div id="map1" tabindex="2" class="map1__x grow h-full
    bg-#84b9bf relative" @click="showCoordinate">
      <div class="absolute z-10 w-50 h-9 bg-white rounded-lg px-2  bottom-1 right-1 flex justify-start items-center" ref="mousePositionTxt" v-show="coordinateSign==1">经纬度：</div>

    </div>
    <div class="bg-white w-80 flex flex-col justify-center items-center">
      <div>用于地区信息展示</div>
      <div>{{points}}</div>
    </div>
  </div>


</template>

<style scoped>

</style>